package com.ganbo.bigevent.exception;

import com.ganbo.bigevent.entity.pojo.Result;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Set;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // @ExceptionHandler(Exception.class)
    // public Result handleException(Exception e){
    //     e.printStackTrace();
    //     return Result.error(StringUtils.hasLength(e.getMessage())? e.getMessage() : "操作失败");
    // }




    @ExceptionHandler(value = Exception.class)
    public Result globalExceptionHandler(Exception e) {
        if (e instanceof BindException) {
            // 参数校验异常
            BindException ex = (BindException) e;
            List<ObjectError> allErrors = ex.getAllErrors();
            ObjectError objectError = allErrors.get(0);
            return Result.error(StringUtils.hasLength(objectError.getDefaultMessage())? objectError.getDefaultMessage() : "操作失败");
        } else if (e instanceof ConstraintViolationException) {
            // 单个参数校验异常
            ConstraintViolationException ex = (ConstraintViolationException) e;
            Set<ConstraintViolation<?>> allErrors = ex.getConstraintViolations();
            return Result.error(StringUtils.hasLength(e.getMessage())? ex.getMessage() : "操作失败");
        } else if (e instanceof MethodArgumentNotValidException) {
            // 单个参数校验异常
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            BindingResult result = ex.getBindingResult();
            FieldError fieldError = result.getFieldError();
            return Result.error(StringUtils.hasLength(e.getMessage())? e.getMessage() : "操作失败");
        } else {
            log.error("系统异常", e);
            return Result.error(StringUtils.hasLength(e.getMessage())? e.getMessage() : "操作失败");
        }
    }
}
